package com.ruoyi.common.utils.encryption;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @author dingwei
 * @date 2022/7/26 13:41
 * @description TODO 请求头加密工具类
 */
public class Md5Encryption {

    private static final Logger logger = LoggerFactory.getLogger(Md5Encryption.class);

    private static final String APP_SECRET = "uWo1OBC0ECSAk8JoeyFwwWbgM0mnBU";

    /**
     * 请求头加密
     *
     * @param requestTime 时间戳
     * @param appKey 访问用户隐私数据时的唯一权限标识
     * @return
     * @throws Exception
     */
    public static String encryption(String requestTime,String appKey) {
        try {
            return md5(requestTime,appKey);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * md5 求值
     *
     * @param data
     * @param key
     * @return
     */
    public static String md5(String data, String key) {
        String sign = DigestUtils.md5Hex(key + APP_SECRET + data);
        return sign;
    }

    /**
     * 签名校验
     *
     * @param request
     * @return
     */
    public static boolean signatureCheck(HttpServletRequest request) {
        String appKey = request.getHeader("appKey");
        logger.info("第三方传过来的appKey：{}", appKey);
        String requestTime = request.getHeader("requestTime");
        logger.info("当前时间戳：{}", requestTime);
        String sign = request.getHeader("sign");
        logger.info("请求头签名：{}", sign);
        String encryption = encryption(requestTime, appKey);
        //校验请求头加密信息是否正确
        return StringUtils.pathEquals(encryption, sign);
    }

}
